// pages/run/run.js
import WxValidate from "../../utils/WxValidate"
import utils from "../../utils/util"
const dateUtils = require('../../utils/dateutils.js');
const app = getApp()

Page({
  handleFooter() {
    wx.showModal({
      cancelColor: "#000",
      title: "用户需知",
      content: "这里是隐私条款具体内容",
      showCancel: false,
    });
  },

  /*** 页面的初始数据 */
  data: {
    //选择时间
    isShowDatePicker: false,
    date: new Date().getTime(),
    //邮件地址
    //multiArray是二维数组，picker多列选择器只支持二维数组
    start_multiArray: [
      ["学校", "车站"],
      ["东一门", "大活东门", "东三门", "南门", "南二门"],
    ], //multiIndex数组，存放 “选中列” 的 “选中值” 对应的下标
    end_multiArray: [
      ["学校", "车站"],
      ["东一门", "大活东门", "东三门", "南门", "南二门"],
    ], //multiIndex数组，存放 “选中列” 的 “选中值” 对应的下标
    start_multiIndex: [0, 0],
    end_multiIndex: [0, 0],
    genderArray: ['不限'],
    numberArray: [2],
    form: {
      startAddress: '请选择出发地', //出发地
      endAddress: '请选择目的地', //目的地 
      startTime: '请选择出发时间', //出发时间
      period: null, //时差范围
      genderLimit: '不限',  //性别要求
      number: null, //组团人数
      phoneNumber: app.globalData.userInfo.phone, //手机号码
      email: '', //邮箱地址
    },
  },
  //多列选择器-值改变时触发
  pickerChange: function (e) {
    console.log(e)
    const {
      which
    } = e.currentTarget.dataset;
    switch (which) {
      case 'start':
        this.setData({
          start_multiIndex: e.detail.value,
          'form.startAddress': `${this.data.start_multiArray[0][this.data.start_multiIndex[0]]}-${this.data.start_multiArray[1][this.data.start_multiIndex[1]]}`,
        });
        break;
      case 'end':
        this.setData({
          end_multiIndex: e.detail.value,
          'form.endAddress': `${this.data.end_multiArray[0][this.data.end_multiIndex[0]]}-${this.data.end_multiArray[1][this.data.end_multiIndex[1]]}`,
        });
        break;
    }
  },
  //多列选择器-列改变时触发
  pickerColumnChange: function (e) {
    const {
      which
    } = e.currentTarget.dataset;
    switch (which) {
      case 'start':
        var data = {
          start_multiArray: this.data.start_multiArray,
          start_multiIndex: this.data.start_multiIndex,
        }; //存放 对应列 选中值 的下标 //e.detail.column 取值范围 0 1 2
        data.start_multiIndex[e.detail.column] = e.detail.value; //根据当前选择的列，更新后面列的值，当e.
        switch (e.detail.column) {
          case 0: //当前滑动操作了第0列
            switch (data.start_multiIndex[0]) {
              case 0: //学校
                data.start_multiArray[1] = [
                  "东一门", "大活东门", "东三门", "南门", "南二门"
                ];
                break;
              case 1: //车站
                data.start_multiArray[1] = [
                  "临沂站", "临沂北站", "启阳机场",
                ];
                break;
            } //后面一列默认 选择为第0个元素
            data.start_multiIndex[1] = 0;
            break;
        }
        //console.log(data.multiIndex);
        this.setData(data);
        break;
      case 'end':
        var data = {
          end_multiArray: this.data.end_multiArray,
          end_multiIndex: this.data.end_multiIndex,
        }; //存放 对应列 选中值 的下标 //e.detail.column 取值范围 0 1 2
        data.end_multiIndex[e.detail.column] = e.detail.value; //根据当前选择的列，更新后面列的值，当e.
        switch (e.detail.column) {
          case 0: //当前滑动操作了第0列
            switch (data.end_multiIndex[0]) {
              case 0: //学校
                data.end_multiArray[1] = [
                  "东一门", "大活东门", "东三门", "南门", "南二门"
                ];
                break;
              case 1: //车站
                data.end_multiArray[1] = [
                  "临沂站", "临沂北站", "启阳机场",
                ];
                break;
            } //后面一列默认 选择为第0个元素
            data.end_multiIndex[1] = 0;
            break;
        }
        this.setData(data);
        break;
    }
  },
  //免责声明
  showStatment() {
    wx.showModal({
      title: "用户条款&隐私策略",
      content: "这里是隐私条款具体内容",
      showCancel: false,
    });
  },

  //性别改变
  genderChange(e){
    console.log(e.detail.value)
    this.setData({
      "form.genderLimit": e.detail.value
    })
  },

  //人数改变
  numberChange(e){
    const number = e.detail.value;
    this.setData({
      "form.number": number,
    });
  switch(number){
    case '3':
    case '4':
      wx.showToast({
        title: '注意行李是否过载',
        icon: 'none',
        duration: 1500
      })
  }
  },

  timeID: 0, //定时器ID
  handleInput(e) {
    const {
      name
    } = e.currentTarget.dataset
    const {
      value
    } = e.detail
    clearTimeout(this.timeID);
    //清除timeID对应的定时器，即取消相应函数的执行
    this.timeID = setTimeout(() => {
      switch (name) {
        case "period":
          this.setData({
            'form.period': value
          })
          break;
        case "email":
          this.setData({
            'form.email': value
          })
          break;
      }
    }, 100)
  },
  //保存表单 
   async submitForm() {
    //判断当前用户是否已授权登录 
    const r = await utils.cklogin(app.globalData.userInfo)
    if (!r) {
      return false
    }
    const {
      startAddress,
      endAddress,
      startTime,
      period,
      genderLimit,
      number,
      phoneNumber,
      email
    } = this.data.form;
    //params为需要验证的数据对象 
    const params = {
      startAddress,
      endAddress,
      startTime,
      period,
      genderLimit,
      number,
      phoneNumber,
      email
    }
    //检测表单数据
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      utils.showValidateModal(error);
      return false
    }
    wx.showLoading({
      title: '请稍等',
    })
    const publicTime = utils.formatTime(new Date());
    wx.request({
      url: `${app.globalData.server}/addCarPoolOrder`,
      method: 'POST',
      data: {
        openid: app.globalData.userInfo.openid,
        orderType: '拼车匹配',
        startAddress: params.startAddress,
        endAddress: params.endAddress,
        publicTime,
        status: '正在拼',
        info: {
          startTime,
          period,
          genderLimit,
          number,
          phoneNumber,
          email
        },
        userInfo: app.globalData.userInfo
      },
      success: (res) => {
        wx.hideLoading({})
          wx.showToast({
            title: res.data.message,
            icon: res.data.code==='success'?'success':'none'
          })
          if(res.data.code==='success'){
            setTimeout(() => {
              wx.switchTab({
                url: '../order/order',
              })
            }, 1000);
          }
      },
      fail: (err) => {
        wx.hideLoading({})
        wx.showToast({
          title: '发布失败',
          icon: 'error'
        })
      }
    })
  },
  /*** 生命周期函数--监听页面加载 */
  onLoad(options) {
    this.initValidate();
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      startAddress: {
        required: true,
        start: true
      },
      endAddress: {
        required: true,
        end: true
      },
      startTime: {
        required: true,
        time: true
      },
      period: {
        required: true,
        min: 10,
        max: 120
      },
      number:{
        required: true,
      },
      phoneNumber: {
        required: true,
        tel: true
      },
      email: {
        required: true,
        email: true
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息 
    const messages = {
      startAddress: {
        required: '请选择出发地',
      },
      endAddress: {
        required: '请选择目的地',
      },
      startTime: {
        required: '请选择出发时间'
      },
      period:{
        required: '请填写可等候时间',
        min: '至少要有10分钟的等候时间哦',
        max: '您的等候时间是不是有点久呢'
      },
      number:{
        required: '请选择组团人数'
      },
      phoneNumber: {
        required: '请授权手机号',
        length: '请检查手机号'
      },
      email: {
        required: '请输入邮件地址，用于通知拼团信息'
      }
    }
    // 创建实例对象 
    this.WxValidate = new WxValidate(rules, messages);
    // 自定义验证规则
    this.WxValidate.addMethod('start', (value, param) => {
      return this.WxValidate.optional(value) || value!=='请选择出发地'
    }, '请选择出发地')
    this.WxValidate.addMethod('end', (value, param) => {
      return this.WxValidate.optional(value) || value!=='请选择目的地'
    }, '请选择目的地')
    this.WxValidate.addMethod('time', (value, param) => {
      return this.WxValidate.optional(value) || value!=='请选择出发时间'
    }, '请选择出发时间')
  },


  //选择出发时间
  chooseTime(e) {
    this.setData({
      isShowDatePicker: true
    })
    this.setData({
      'date': new Date().getTime(),
    })
  },
  //取消出发时间
  datePickerCancellEvent: function (e) {
    this.setData({
      isShowDatePicker: false
    })
  },
  //确定出发时间
  datePickerOkEvent: function (e) {
    this.setData({
      isShowDatePicker: false
    })
    let date = e.detail.date;
    this.setData({
      'form.startTime': dateUtils.formatLongTime(date, "Y-M-D h:m")
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //读取全局变量userInfo 
    const {
      userInfo
    } = app.globalData;
    this.setData({
      'form.phoneNumber': userInfo.phone ? userInfo.phone : '请授权手机号',
      'form.email': userInfo.email,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});